package ejb;

import java.sql.Timestamp;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import model.Apply;
import model.Myuser;
import model.Target;

/**
 * Session Bean implementation class ApplyFacadeEJB
 */


@Stateless
public class ApplyFacadeEJB implements ApplyFacadeEJBRemote {

	@PersistenceContext
	EntityManager em;
    
	@Override
    public boolean createApply(Myuser u, Target t, String reason, String status){

		java.util.Date date= new java.util.Date();
		Timestamp time = new Timestamp(date.getTime());
    	Apply app = new Apply();
    	app.setMyuser(u);
    	app.setTargetBean(t);
    	app.setReason(reason);
    	app.setApplyStatus(status);
    	app.setApplyDate(time);
    	
		try{
			em.persist(app);
		}catch(Exception e){
			e.printStackTrace();
		}
		return true;
    }
	
	@Override
    public boolean ifApplyExist(Myuser u, Target t){
		
		String sql="select a from Apply a where a.myuser=:u and a.targetBean=:t";
    	Query query= em.createQuery(sql);
    	query.setParameter("u", u);
    	query.setParameter("t",t);
    	if(query.getResultList().isEmpty()){
    		return false;
    	}
    	else return true;
		
	}
	
	@Override
    public boolean setAppStatus(Apply app, String status){
		try{
		app.setApplyStatus(status);
		}catch(Exception e){
		}
		return true;
	}

	@Override
	public List<Apply> getAllWaitingApply() {
		String sql="select a from Apply a where a.applyStatus=:s";
    	Query query= em.createQuery(sql);
    	query.setParameter("s", "waiting");
    	return (List<Apply>) query.getResultList();
	}

	@Override
	public boolean approveApplyById(int id, boolean isApprove) {
		String sql="select a from Apply a where a.applyStatus=:s and a.applyid=:d";
		Query query = em.createQuery(sql);
		query.setParameter("s", "waiting");
		query.setParameter("d", id);
		List<Apply> applyList = (List<Apply>) query.getResultList();
		Apply app=null;
		if(applyList.size()!=0){
			app = applyList.get(0);
//			if(isApprove){
//				app.setApplyStatus("pass");
//			}else{
//				app.setApplyStatus("denied");
//			}
			
			try{
				em.remove(em.merge(app));
			}catch(Exception e){
				e.printStackTrace();
			}
			
			return true;
		}		
		
		return false;
	}

	@Override
	public Apply getApplyById(int id) {
		String sql="select a from Apply a where a.applyid=:d";
		Query query = em.createQuery(sql);
		query.setParameter("d", id);
		
		List<Apply> applyList = (List<Apply>) query.getResultList();
		Apply app=null;
		if(applyList.size()!=0){
			return applyList.get(0);
		}else{
			return null;
		}
		
	}

    

}
